package com.sirc.zp.web.controllers;

import com.sirc.zp.domain.User;
import com.sirc.zp.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

/**
 * 和登陆相关的Controller
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserService userService;
    /**
     * 从前台获得User，验证用户名密码。
     * @return
     */
    @RequestMapping("/go")
    public String login(User user) {
        //使用shiro验证用户名密码
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token =new
                UsernamePasswordToken(user.getUsername(),user.getPassword());
        try {
            //用户登录
            subject.login(token);
        }catch (Exception e)
        {
            //登录失败，返回login页面
            return "redirect:/";
        }
        //登录成功，更新用户的最新登录时间
        //跳转页面
        User u=(User)subject.getSession().getAttribute("user");
        u.setLasttime(new Date());
        userService.updateUser(u);
        return "redirect:/index/success";
    }
}
